package com.sangcomz.fishbun.ui.picker;

import com.sangcomz.fishbun.ResourceTable;
import com.sangcomz.fishbun.adapter.image.ImageAdapter;
import com.sangcomz.fishbun.ui.picker.listener.OnPickerActionListener;
import com.sangcomz.fishbun.ui.picker.model.PickerListItem;
import com.sangcomz.fishbun.ui.picker.model.PickerRepository;
import com.sangcomz.fishbun.ui.picker.model.PickerViewData;
import com.sangcomz.fishbun.util.BaseGridSliceProvider;
import com.sangcomz.fishbun.util.RadioWithTextButton;
import com.sangcomz.fishbun.util.ThreadPoolUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.utils.net.Uri;

import java.io.IOException;
import java.util.*;

public class PickerProvider extends BaseGridSliceProvider<PickerListItem, BaseGridSliceProvider.BaseViewHolder> {

    private ImageAdapter imageAdapter;
    private OnPickerActionListener onPickerActionListener;
    private boolean hasCameraInPickerPage;
    private static final int TYPE_CAMERA = Integer.MIN_VALUE;
    private static final String UPDATE_PAYLOAD = "payload_update";

    public PickerProvider(Context context,
                          ImageAdapter imageAdapter,
                          OnPickerActionListener onPickerActionListener,
                          GridConfig gridConfig,
                          boolean hasCameraInPickerPage) {
        super(context, new ArrayList<>(), ResourceTable.Layout_picker_item,gridConfig);

        this.imageAdapter = imageAdapter;
        this.onPickerActionListener = onPickerActionListener;
        this.hasCameraInPickerPage = hasCameraInPickerPage;
    }

    public void setPickerList(List<PickerListItem> pickerList) {
        if (pickerList != null) {
            itemData = pickerList;
            notifyDataChanged();
        }
    }

    public void  addImage(PickerListItem.Image path) {
        //TODO 添加图片
    }

    public void updatePickerListItem(int position, PickerListItem.Image image) {
        if (itemData != null) {
            itemData.set(position, image);
        }

        if (image.getSelectedIndex() == -1) {
            onPickerActionListener.onDeselect();
        } else {
            notifyDataChanged();
        }
    }

    public void updatePickerListItem(PickerRepository pickerRepository) {
        if (itemData != null) {
            for (PickerListItem item : itemData) {
                if (item instanceof PickerListItem.Image) {
                    int index = pickerRepository.getSelectedIndex(((PickerListItem.Image) item).getImageUri());
                    ((PickerListItem.Image) item).setSelectedIndex(index);
                }
            }
        }
        notifyDataChanged();
    }

    @Override
    public void onBindViewHolder(BaseGridSliceProvider.BaseViewHolder viewHolder, PickerListItem data, int viewType, int position, int indexPosition) {
        if (viewHolder instanceof ViewHolderImage) {
            ((ViewHolderImage)viewHolder).bindData(data,position);
        }
    }

    @Override
    public BaseViewHolder onCreateViewHolder(Component component, int viewType) {
//        switch (viewType) {
//            case TYPE_CAMERA:
//                return new ViewHolderCamera(component);
//            default:
//                return new ViewHolderImage(component);
//        }
        return new ViewHolderImage(component);
    }

//    @Override
//    public int getItemViewType(int position) {
//        if (position == 0 && hasCameraInPickerPage) {
//            return TYPE_CAMERA;
//        } else {
//            return 0;
//        }
//    }

    @Override
    public int getItemResId(int type) {
        if (type == TYPE_CAMERA) {
            return ResourceTable.Layout_header_item;
        } else {
            return ResourceTable.Layout_picker_item;
        }
    }

    class ViewHolderCamera extends BaseViewHolder {

        public ViewHolderCamera(Component component) {
            super(component);
        }
    }

    class ViewHolderImage extends BaseViewHolder {

        Image imgThumbImage;
        RadioWithTextButton btnThumbCount;
        Component component;

        public ViewHolderImage(Component component) {
            super(component);
            this.component = component;
            imgThumbImage = (Image) component.findComponentById(ResourceTable.Id_img_thumb_image);
            btnThumbCount = (RadioWithTextButton) component.findComponentById(ResourceTable.Id_btn_thumb_count);
        }

        public void bindData(PickerListItem item,int position) {

            if (!(item instanceof PickerListItem.Image)) {
                return;
            }
            System.out.printf("===bindData===>"+((PickerListItem.Image) item).getSelectedIndex());


            PickerViewData viewData = ((PickerListItem.Image) item).getViewData();
            if (btnThumbCount != null) {
                btnThumbCount.setCircleColor(viewData.getColorActionBar());
                btnThumbCount.setTextColor(viewData.getColorActionBarTitle());
                btnThumbCount.setStrokeColor(viewData.getColorSelectCircleStroke());
                btnThumbCount.unselect();

                btnThumbCount.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        onPickerActionListener.onClickThumbCount(position);
                    }
                });
            }

            if (imgThumbImage != null) {
                imgThumbImage.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        onPickerActionListener.onClickImage(position);
                    }
                });
            }

            initState(((PickerListItem.Image) item).getSelectedIndex(), viewData.getMaxCount() == 1);
            Uri oldUri = (Uri) imgThumbImage.getTag();
            Uri itemImageUri = ((PickerListItem.Image) item).getImageUri();
            if (oldUri == null || !oldUri.toString().equals(itemImageUri.toString())) {
                imageAdapter.loadImage((AbilitySlice) getContext(), imgThumbImage, itemImageUri);
            }
            imgThumbImage.setTag(itemImageUri);
            update(item);
        }

        private void initState(int selectedIndex, boolean isUseDrawable) {

            if (selectedIndex != -1) {
                setScale(imgThumbImage, true);
                setRadioButton(isUseDrawable,(selectedIndex + 1) + "");
            } else {
                setScale(imgThumbImage, false);
            }
        }

        public void update(PickerListItem item) {

            if (!(item instanceof PickerListItem.Image)) {
                return;
            }
            int selectedIndex = ((PickerListItem.Image) item).getSelectedIndex();
            animScale(imgThumbImage, selectedIndex != -1, true);

            if (selectedIndex != -1) {
                setRadioButton(((PickerListItem.Image) item).getViewData().getMaxCount() == 1, (selectedIndex + 1) + "");
            } else {
                btnThumbCount.unselect();
            }
        }

        private void animScale(Component view, boolean isSelected, boolean isAnimation) {
            //TODO 暂时屏蔽掉动画
//            int duration = 200;
//            if (!isAnimation) duration = 0;
//            float toScale = isSelected ? 0.8f : 1.0f;
//            AnimatorValue animatorValue = new AnimatorValue();
//            animatorValue.setDuration(duration);
//            animatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
//                @Override
//                public void onUpdate(AnimatorValue animatorValue, float v) {
//                    float scale = 1 - (1 - toScale) * v;
//                    view.setScaleX(scale);
//                    view.setScaleY(scale);
//                }
//            });
//            animatorValue.start();
//            if (!isSelected) {
//                onPickerActionListener.onDeselect();
//            }
        }

        private void setScale(Component view, boolean isSelected) {
            float toScale = isSelected ? 0.8f : 1.0f;
            view.setScaleX(toScale);
            view.setScaleY(toScale);
        }

        private void setRadioButton(boolean isUseDrawable, String text) {

            if (isUseDrawable) {
                try {
                    Resource resource = getContext().getResourceManager().getResource(ResourceTable.Media_ic_done_white_24);
                    PixelMapElement pixBg = new PixelMapElement(resource);
                    btnThumbCount.setDrawable(pixBg);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (NotExistException e) {
                    e.printStackTrace();
                }
            } else {
                btnThumbCount.setText(text);
            }
        }
    }

}
